<template>
    <div :class="['switcher-wrapper', checked ? 'checked-bg' : 'unchecked-bg', disabled ? 'disabled':'']"
         :style="wStyle" @click="change">
        <div class="switcher-toggle" ref="icon" :style="iStyle"></div>
    </div>
</template>

<style scoped>
.switcher-wrapper {
    width: 80px;
    height: 40px;
    border-radius: 49px;
    justify-content: center;
}
.unchecked-bg {
    background-color: #d0d0d0;
}
.checked-bg {
    background-color: #e31336;
}
.switcher-toggle {
    width: 36px;
    height: 36px;
    border-radius: 18px;
    background-color: #fff;
    margin-left: 3px;
}
.disabled {
    background-color: #d0d0d0;
}
</style>

<script type="text/ecmascript-6">
    let animation = weex.requireModule('animation');
    export default{
        props: {
            wStyle: {
                type: Object,
                default: {}
            },
            iStyle: {
                type: Object,
                default: {}
            },
            disabled: {
                type: Boolean,
                default: false
            },
            checked: {
                type: Boolean,
                default: false
            }
        },
        data(){
            return {
            }
        },
        mounted () {
            this.$nextTick(() => {
                if (this.checked) {
                    this.move(0);
                }
            })
        },
        methods: {
            change(){
                if (!this.disabled) {
                    this.checked = !this.checked;
                    this.move();
                    this.$emit('change', this.checked);
                }
            },
            move(time, callback){
                let trans = this.checked ? 'translateX(38px)' : 'translateX(0)';
                animation.transition(this.$refs.icon, {
                    styles: {
                        transform: trans
                    },
                    duration: time || 300, //ms
                    delay: 0, //ms
                    timingFunction: 'linear'
                }, ()=> {
                    if(typeof callback === 'function') {
                        callback();
                    }
                });
            }
        }
    }
</script>
